import Vue from "vue";
import Router from "vue-router";
import Layout from "@/components/layout";
import vstore from '@/store'
import { getRouters } from '@/api/menu'
import { getButPermissions } from "@/api/power/user";
import { recursionData, mapTree, filPath } from '@/utils/validate.js'
import { Message } from 'element-ui'

export const loadView = view => {
  // 路由懒加载
  return resolve => require([`@/views/${view}`], resolve);
};
var getRouter;
var redirectStr = 0;
Vue.use(Router);

let prefix = ''
if (window.__POWERED_BY_QIANKUN__) {
  prefix = '/digitalTwinApply'
}

export const constantRoutes = [
  {
    path: prefix + "/",
    component: Layout,
    redirect: prefix + "/login",
    children: [
      {
        path: prefix + "/institution",
        component: resolve => require(["@/views/power/institution"], resolve)
      },
      {
        path: prefix + "/loadpotential",
        component: resolve =>
          require(["@/views/loadforecasting/loadpotential/index"], resolve)
      },
      {
        path: prefix + "/dayAheadLoadForecast",
        component: resolve =>
          require([
            "@/views/loadforecasting/dayAheadLoadForecast/index"
          ], resolve)
      }
    ]
  },
  {
    path: prefix + "/",
    component: Layout,
    redirect: prefix + "/courtsTpologyMintenance",
    children: [
      {
        //首页-------最初版
        path: prefix + "/home",
        component: resolve =>
          require([
            "@/views/carNetworkInteraction/home/index"
          ], resolve)
      },
      {
        //首页-------第二版
        path: prefix + "/homepages",
        component: resolve =>
          require([
            "@/views/carNetworkInteraction/home/one"
          ], resolve)
      },
      {
        path: prefix + "/evaluation",
        component: resolve =>
          require([
            "@/views/risk/evaluation"
          ], resolve)
      },
      {
        path: prefix + "/indicator",
        component: resolve =>
          require([
            "@/views/risk/riskItem"
          ], resolve)
      },
      {
        path: prefix + "/riskRule",
        component: resolve =>
          require([
            "@/views/risk/riskRule"
          ], resolve)
      },
      {
        path: prefix + "/riskTask",
        component: resolve =>
          require([
            "@/views/risk/riskTask"
          ], resolve)
      },
      {
        path: prefix + "/riskReport",
        component: resolve =>
          require([
            "@/views/risk/riskReport"
          ], resolve)
      },
      //巡检
      {
        path: prefix + "/configuration",
        component: resolve =>
          require([
            "@/views/inspection/configuration"
          ], resolve)
      },
      {
        path: prefix + "/plan",
        component: resolve =>
          require([
            "@/views/inspection/plan"
          ], resolve)
      },
      {
        path: prefix + "/patro",
        component: resolve =>
          require([
            "@/views/inspection/patro"
          ], resolve)
      },
      //日志
      {
        path: prefix + "/record",
        component: resolve =>
          require([
            "@/views/log/record"
          ], resolve)
      },
      //告警
      {
        path: prefix + "/alarmQuery",
        component: resolve =>
          require([
            "@/views/alarm/alarmQuery"
          ], resolve)
      },
      //运营分析
      {
        path: prefix + "/damage",
        component: resolve =>
          require([
            "@/views/analysis/damage"
          ], resolve)
      },
      {
        path: prefix + "/charging",
        component: resolve =>
          require([
            "@/views/analysis/charging"
          ], resolve)
      },
      {
        //台区检测
        //台区拓补维护
        path: prefix + "/courtsTpologyMintenance",
        component: resolve =>
          require([
            "@/views/carNetworkInteraction/courtsDtection/courtsTpologyMintenance/index"
          ], resolve)
      },
      {
        //台区负荷检测
        path: prefix + "/courtsLoadDtection",
        component: resolve =>
          require([
            "@/views/carNetworkInteraction/courtsDtection/courtsLoadDtection/index"
          ], resolve)
      },
      {
        //场站监测
        //维护影响因素库
        path: prefix + "/maintenanceImpactFactorsLibrary",
        component: resolve =>
          require([
            "@/views/carNetworkInteraction/loadPredictLibrary/maintenanceImpactFactorsLibrary/index"
          ], resolve)
      },
      // {
      //   //算法设置
      //   path: "/algorithmSetting",
      //   component: resolve =>
      //     require([
      //       "@/views/carNetworkInteraction/loadPredictLibrary/algorithmSetting/index"
      //     ], resolve)
      // },

      //补贴管理
      {
        path: prefix + "/subsidy",
        component: resolve => require(["@/views/carNetworkInteraction/subsidy/index"], resolve)
      },
      {
        //负荷分布
        path: prefix + "/loadDstribution",
        component: resolve =>
          require([
            "@/views/carNetworkInteraction/StationMonitoring/loadDstribution/index"
          ], resolve)
      },
      {
        //场站负荷监测
        path: prefix + "/terminalLoadMonitoring",
        component: resolve =>
          require([
            "@/views/carNetworkInteraction/StationMonitoring/terminalLoadMonitoring/index"
          ], resolve)
      },

      {
        //日前负荷预测
        path: prefix + "/recentlyLoadPredict",
        component: resolve =>
          require([
            "@/views/carNetworkInteraction/loadPredictLibrary/recentlyLoadPredict/index"
          ], resolve)
      },
      {
        //日前预测曲线
        path: prefix + "/curve",
        component: resolve =>
          require([
            "@/views/carNetworkInteraction/loadPredictLibrary/curve/index"
          ], resolve)
      },
      {
        //可调潜力同步
        path: prefix + "/adjustablePotentialSynchronization",
        component: resolve =>
          require([
            "@/views/carNetworkInteraction/loadPredictLibrary/adjustablePotentialSynchronization/index"
          ], resolve)
      },
      // {
      //   //社会运营商管理
      //   path: "/recordManagement",
      //   component: resolve =>
      //     require([
      //       "@/views/carNetworkInteraction/socialOperatorManagement/recordManagement/index"
      //     ], resolve)
      // },
      // {
      //   //运营商效果评估
      //   path: "/OperatorEffectAssessment",
      //   component: resolve =>
      //     require([
      //       "@/views/carNetworkInteraction/socialOperatorManagement/OperatorEffectAssessment/index"
      //     ], resolve)
      // },
      {
        path: prefix + "/interactiveEventEffectEvaluation",
        component: resolve =>
          require([
            "@/views/carNetworkInteraction/evaluationEffect/interactiveEventEffectEvaluation/index"
          ], resolve)
      },
      {
        //补贴管理
        path: prefix + "/managementSubsidies",
        component: resolve =>
          require([
            "@/views/carNetworkInteraction/evaluationEffect/managementSubsidies/index"
          ], resolve)
      },
      // {
      //
      //   //计划编制
      //   path: "/preparationPlans",
      //   component: resolve =>
      //     require([
      //       "@/views/carNetworkInteraction/interactiveControl/preparationPlans/index"
      //     ], resolve)
      // },

      //互动调控
      {
        //互动事件
        path: prefix + "/interactivEevents",
        component: resolve =>
          require([
            "@/views/carNetworkInteraction/interactiveControl/interactivEevents/index"
          ], resolve)
      },
      {
        //调控分组
        path: prefix + "/controlSubgroup",
        component: resolve =>
          require([
            "@/views/carNetworkInteraction/interactiveControl/controlSubgroup/index"
          ], resolve)
      },
      {
        //聚合单元管理
        path: prefix + "/aggregationunitManagement",
        component: resolve =>
          require([
            "@/views/carNetworkInteraction/interactiveControl/aggregationunitManagement/index"
          ], resolve)
      },
      // {
      //   //调控管理
      //   path: "/regulationControl",
      //   component: resolve =>
      //     require([
      //       "@/views/carNetworkInteraction/interactiveControl/regulationControl/index"
      //     ], resolve)
      // },
      {
        //有序充电
        //台区事件
        path: prefix + "/platformAreaIncident",
        component: resolve =>
          require([
            "@/views/carNetworkInteraction/orderlyCharging/platformAreaIncident/index"
          ], resolve)
      },
      {
        //有序充电管理
        path: prefix + "/orderlyChargingManagement",
        component: resolve =>
          require([
            "@/views/carNetworkInteraction/orderlyCharging/orderlyChargingManagement/index"
          ], resolve)
      },
      {
        //故障诊断管理
        path: prefix + "/faultManagement",
        component: resolve =>
            require([
              "@/views/carNetworkInteraction/fault/faultManagement/index"
            ], resolve)
      },
      {
        //知识库管理
        path: prefix + "/knowledgeManagement",
        component: resolve =>
            require([
              "@/views/carNetworkInteraction/fault/knowledgeManagement/index"
            ], resolve)
      },
      {
        //知识库管理
        path: prefix + "/knowledgeBaseManagement",
        component: resolve =>
          require([
            "@/views/carNetworkInteraction/fault/knowledgeBaseManagement/index"
          ], resolve)
      }
    ]
  },
  {
    path: prefix + "/login",
    component: resolve => require(["@/views/login"], resolve)
  },
  {
    path: prefix + "*",
    component: resolve => require(["@/views/error/404"], resolve)
  },
  {
    path: prefix + "/401",
    component: resolve => require(["@/views/error/401"], resolve)
  }
];

var router = new Router({
  mode: "hash",
  // base: window.__POWERED_BY_QIANKUN__ ? '/digitalTwinApply/' : '/',
  routes: constantRoutes
});

//过滤函数
function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter(route => {
    if (route.component) {
      if (route.component === "Layout") {
        route.component = Layout;
      } else {
        route.name == "operate/sitemore" ? (route.meta.keepAlive = true) : "";
        route.component = loadView(route.component);
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children);
    }
    return true;
  });
}
function filters(data) {
  var newData = data.filter(x => x);
  newData.forEach(x => x.children && (x.children = filters(x.children)));
  return newData;
}

if (window.__POWERED_BY_QIANKUN__) {
  // 拦截
  router.beforeEach((to, from, next) => {
    // 判断该路由是否需要登录权限
    if (to.path != '/login') {
      if (!to.path.includes(prefix)) {
        if (to.meta.title != null) {
          if (vstore.state.tab.length < vstore.state.v_num) {
            vstore._mutations.addTab[0](
              {
                "name": to.meta.title,
                "path_": to.name,
                "path": to.path,
                "lock": false
              }
            )
          } else {
            let sign = vstore.state.tab.every(item => {
              return item.path != to.path
            })  //不存在 push
            let sign2 = vstore.state.v_showData.every(item => {
              return item.path != to.path
            })  //不存在 push
            if (sign && sign2) {
              vstore._mutations.add_v_showData[0](
                {
                  "name": to.meta.title,
                  "path": to.path,
                  "lock": false
                }
              )
            }
          }
        }
        if (sessionStorage.getItem("isLogin")) {
          if (!getRouter) {
            if (!getObjArr('router')) {
              getRouters().then(res => {
                if (res.data.length > 0) {
                  let quesData = []
                  res.data.map(item => {
                    // item.name='mp/'+item.name
                    quesData.push(mapTree(item))
                  })
                  quesData = filters(quesData)
                  getRouter = recursionData((quesData).sort(function (a, b) { return a.orderNum - b.orderNum }))//后台拿到路由
                  let dataRou = JSON.parse(JSON.stringify(getRouter));

                  redirectStr = "";

                  mapTree_redirectStr(dataRou[0])  //层
                  getRouter.unshift({
                    path: prefix +'/',
                    redirect: prefix + '/' + redirectStr.split('/').filter(item => { return item != "" }).reverse().join('/') //处理过的重定向
                  })

                  vstore._mutations.setRourer[0](getRouter);
                  // console.log(getRouter,'____________________看看路由1111111')
                  saveObjArr('router', getRouter)
                  routerGo(to, next)
                  getButPermissions().then(res => {
                    vstore._mutations.SET_PERMISSIONS[0](res.data)
                  })
                } else {
                  Message({
                    message: '没有请求到菜单',
                    type: 'error',
                    duration: 3 * 1000
                  });
                  next({
                    path: prefix + '/login'
                  })
                  getRouter = null;
                  saveObjArr("router", [])
                }
              })
            } else {
              getRouter = getObjArr('router')
              vstore._mutations.setRourer[0](getRouter);
              routerGo(to, next)
            }
          } else {
            next()
          }
        } else {
          next({
            path: prefix + '/login'
          })
          saveObjArr("router", [])
          getRouter = null;
        }
      } else {
        next()
      }
    } else {
      saveObjArr("router", [])
      getRouter = null;
      next()
    }
  })
}


function routerGo(to, next) {
  getRouter = filterAsyncRouter(getRouter);
  console.log(getRouter, "____________12341231234");
  router.addRoutes(getRouter);
  next({ ...to, replace: true });
}

export function saveObjArr(name, data) {
  localStorage.setItem(name, JSON.stringify(data));
}

export function getObjArr(name) {
  return JSON.parse(localStorage.getItem(name));
}

function mapTree_redirectStr(org) {
  const haveChildren = Array.isArray(org.children) && org.children.length > 0;
  if (haveChildren) {
    mapTree_redirectStr(org.children[0]);
  }
  redirectStr += "/" + org.path;
}

export function updetaMenu() {
  //	getRouters().then(res => {
  //	    getRouter = recursionData((res.data).sort(function(a,b){return a.orderNum - b.orderNum}))
  //	    getRouter.push(
  //		         	{
  //					    path: '/data',
  //					    component: 'Layout',
  //					    children:[
  //						    {
  //								path: 'indexdata',
  //								component: 'data/indexdata',
  //								meta:{title:'资料管理'}
  //							},
  //					    ]
  //					}
  //		         )
  //		         getRouter.push(
  //		         	{
  //					    path: '/system',
  //					    component: 'Layout',
  //					    children:[
  //						    {
  //								path: 'inspectlib',
  //								component: 'system/inspectlib',
  //								meta:{title:'运维预案库'}
  //							},
  //					    ]
  //					}
  //		         )
  //	    vstore._mutations.setRourer[0](getRouter);
  //	    sessionStorage.setItem("router",JSON.stringify(getRouter))
  //	    saveObjArr('router', getRouter)
  //	    getRouter = filterAsyncRouter(getRouter)
  //		router.addRoutes(getRouter)
  //  })
}
//export function newSet(state){
//	let arr2 = state.filter((x, index,self)=>{
//	  let arrids = []
//	  let arrnames = []
//	  state.forEach((item,i) => {
//	    arrids.push(item.path)
//	  })
//	  let judgeOne = arrids.indexOf(x.path) === index
//	  return judgeOne
//	})
//	return arr2
//}

export default router;
